#include <stdlib.h>

char *mem = 0;

unsigned int totalSz = 0;
unsigned int usedSz = 0;

#define EXTRA_INFO_SZ 4

void *alloc(int sz)
{
  int freeMem = totalSz - usedSz;
  if(freeMem < (sz+EXTRA_INFO_SZ)) {
    totalSz += (sz+EXTRA_INFO_SZ) - freeMem;
    mem = (char *) realloc(mem, totalSz);
  }

  char *result = mem+usedSz;

  unsigned int *extraInfo = (unsigned int *)(result + sz);
  *extraInfo = usedSz;
  usedSz += sz+EXTRA_INFO_SZ;

  return result;
}

void *allocAlign(int sz, int align)
{
  align-=1;

  void *resultTmp = alloc(sz+align);

  return (void *)( ((size_t)resultTmp + align) & ~(size_t)align );
}

void dealloc()
{
  unsigned int *lastExtraInfo = (unsigned int *) (mem + usedSz - EXTRA_INFO_SZ);
  usedSz = *lastExtraInfo;
}

void main(void)
{
  alloc(128);
  alloc(128);
  dealloc();
  alloc(120);
  alloc(8);
  alloc(1024);
  dealloc();
  alloc(1023);
  allocAlign(1,4);
  allocAlign(1,4);
  dealloc();
  dealloc();
  dealloc();
  dealloc();
  dealloc();
  dealloc();
}

